package utils

import (
	"center-platform/config"
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"time"
)

var RedisClient *redis.Client
var ctx = context.Background()

func InitRedis() {
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", config.GlobalConfig.Redis.Host, config.GlobalConfig.Redis.Port),
		Password: config.GlobalConfig.Redis.Password,
		DB:       config.GlobalConfig.Redis.DB,
	})
	ping, err := RedisClient.Ping(ctx).Result()
	if err != nil {
		panic("redis连接失败:" + err.Error())
	}
	fmt.Println("--------redis加载成功-------", ping)
}

func Get(key string) string {
	val, err := RedisClient.Get(ctx, key).Result()
	if err != nil {
		return ""
	}
	return val
}

func Set(key string, val interface{}, ttl time.Duration) {
	err := RedisClient.Set(ctx, key, val, ttl).Err()
	if err != nil {
		panic("redis set err:" + err.Error())
	}
}

func Lpush(key string, val interface{}) {
	err := RedisClient.LPush(ctx, key, val).Err()
	if err != nil {
		panic("redis lpush err:" + err.Error())
	}
}

func Rpop(key string) string {
	val, err := RedisClient.RPop(ctx, key).Result()
	if err != nil {
		return ""
	}
	return val
}
